local ngx = require "ngx";
local cjson = require "cjson"
local base64 = require "ngx.base64"
-- local http = require "resty.http"

-- 验证Token
local function verifyToken(url, token)
    local message;
    local resCode = 200;
    local noVerify = false;
    local resStr
    local baseUrl = base64.encode_base64url(url)
    if not token then
        message = '{"code":"401","message":"请求头未携带认证token[H-Authorization]"}';
    else
        local reqBodyData = '{"token":"' .. token .. '","accessUrl":"' .. baseUrl .. '"}';
        local res, err = ngx.location.capture("/verify",
            { method = ngx.HTTP_POST, headers = { ["Content-Type"] = "application/json" }, body = reqBodyData });
        if res then
            if res.status  then
                resStr = res.body
                ngx.ctx.reqClientInfo=resStr;
                local resJson = cjson.decode(resStr);
                resCode = resJson["code"];
                if resCode ~= 200 then
                    message = '{"code":"401","message":"' .. resJson["message"] .. '","data":[]}';
                elseif not resJson["data"]["verify"] then
                    message = '{"code":"402","message":"' .. "Token验证失败" .. '","data":[]}';
                elseif not resJson["data"]["permsVerify"] then
                    message = '{"code":"403","message":"' .. "权限验证失败" .. '","data":[]}';
                else
                    noVerify = true;                    
                end
            else
                message = '{"code":"402","message":"token验证失败"}';
            end
        else
            message = '{"code":"402","message":"token验证失败","errMsg":"' .. err .. '"}';
        end
    end
    return noVerify, resStr, message
end
function endsWith(str, suffix)
    return str:sub(-#suffix) == suffix
end


local h = ngx.req.get_headers();
local host = ngx.req.get_headers()["host"];
local tokenStr = h["H-Authorization"];
local curUrl = ngx.var.scheme .. "://" .. host .. ngx.var.uri .. "/";
if not endsWith(ngx.var.uri,"token") and not endsWith(ngx.var.uri,"/verify") then
    ngx.req.read_body();
    local reqBody=ngx.req.get_body_data();
    if not reqBody then
        reqBody="";
    end
    ngx.ctx.reqBody=reqBody;
    local noverify, tokenData, msg = verifyToken(curUrl, tokenStr);
    if not noverify then
        ngx.header.content_type="application/json";
        ngx.say(msg)
        ngx.eof();
    end
end
